package com.s666.demo.service;
import com.s666.demo.dao.mapper.SysUserMapper;
import com.s666.demo.dao.entity.SysRole;
import com.s666.demo.model.dto.UserRolesDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import com.s666.demo.utils.Aes;
/**
 * @author lijin
 */
@Service
@Slf4j
public class WebUserDetailsService implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Resource
    private SysUserMapper sysUserMapper;

    @Value("${enkey.aes.password-key}")
    private String aesKey;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserRolesDTO userRolesDto =  sysUserMapper.findByUsername(username);
        if (userRolesDto == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }

        //2. 获取权限列表
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        //用于添加用户的权限。只要把用户权限添加到authorities 就万事大吉。
        for (SysRole role : userRolesDto.getRoles()) {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
            //System.out.println(role.getName());
        }

        //3. 获取密码
        String dePassword = Aes.decrypt(userRolesDto.getPassword(), aesKey);

        //log.info("dePassword: {}", dePassword);
        String password = passwordEncoder.encode(dePassword);
//        log.info("password: {}", password);

        return new User(username, password, authorities);
    }
}


    /* 测试用的样例 admin 123456
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("用户的用户名: {}", username);

		String password = passwordEncoder.encode("123456");
        log.info("password: {}", password);

        // 封装用户信息，并返回。参数分别是：用户名，密码，用户权限
        User user = new User(username,password,
                            AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
        return user;
    }*/


